/*
 * @Description  : 登录输入框
 * @Author       : Keyman
 * @Date         : 2025-11-03 16:04:39
 * @LastEditors  : Keyman
 * @LastEditTime : 2025-11-15 01:07:39
 */

import React, { useState } from "react";
import { LockOutlined, UserOutlined } from "@ant-design/icons";
import { Button, Form, Input } from "antd";
import { login } from "../../api/users";
import { useDispatch } from "react-redux";
import { setToken } from "../../store/login/authSlice";
import { useNavigate } from "react-router-dom";

type FieldType = {
  username?: string;
  password?: string;
  remember?: string;
};

const InputBox: React.FC = () => {
  const [form] = Form.useForm();
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);
  const submitHandler = () => {
    form
      .validateFields()
      .then(async (res) => {
        setLoading(true);
        const {
          data: { token, username },
        } = await login(res);
        dispatch(setToken(token));
        sessionStorage.setItem("username", username);
        setLoading(false);
        navigate("/", { replace: true });
      })
      .catch((err) => {
        console.log(err);
      });
  };
  return (
    <Form form={form}>
      <Form.Item<FieldType>
        name="username"
        rules={[
          { required: true, message: "用户名不能为空！  " },
          { pattern: /^\w{4,8}$/, message: "用户名为4-8位数字字母组合" },
        ]}
      >
        <Input placeholder="请输入用户名" prefix={<UserOutlined />} />
      </Form.Item>

      <Form.Item<FieldType>
        name="password"
        rules={[{ required: true, message: "密码不能为空！" }]}
      >
        <Input.Password placeholder="请输入密码" prefix={<LockOutlined />} />
      </Form.Item>

      <Form.Item>
        <Button
          type="primary"
          style={{ width: "100%" }}
          onClick={submitHandler}
          loading={loading}
        >
          登录
        </Button>
      </Form.Item>
    </Form>
  );
};

export default InputBox;
